package com.hskn.hss.module.tlempincidental.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.controller.BaseController;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.tlcarmanufacturer.entity.TlCarManufacturer;
import com.hskn.hss.module.tlemergentplan.entity.TlEmergentPlan;
import com.hskn.hss.module.tlempincidental.entity.TlEmpIncidental;
import com.hskn.hss.module.tlempincidental.mapper.TlEmpIncidentalMapper;
import com.hskn.hss.module.tlempincidental.service.ITlEmpIncidentalService;
import com.hskn.hss.module.tlempincidental.to.*;
import com.hskn.hss.module.tlempincidental.vo.EmpIncidentalExcelOutVO;
import com.hskn.hss.module.tlempincidental.vo.EmpIncidentalForListVO;
import com.hskn.hss.module.tlempincidental.vo.EmpIncidentalInExcelOutVO;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.tltreespec.mapper.TlTreespecMapper;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-19
 */
@Slf4j
@RestController
@RequestMapping("/hss/tlempincidental")
@Api(tags = {"-tl_emp_incidental"}, description = "人员杂费")
public class TlEmpIncidentalController extends BaseController {

    @Autowired
    ITlEmpIncidentalService tlEmpIncidentalService;
    @Resource
    private ITlEmployeeService employeeService;
    @Autowired
    private ISysDepartService departService;

    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_emp_incidental", bean = TlEmpIncidental.class, beanMapper = TlEmpIncidentalMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "人员杂费新增接口", notes = "人员杂费新增")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult insert(@RequestBody @Validated InsertEmpIncidentalTO insertEmpIncidentalTO) {
        try {
            return toAjax(tlEmpIncidentalService.insert(insertEmpIncidentalTO));
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_emp_incidental", idKey = "id", bean = TlEmpIncidental.class, beanMapper = TlEmpIncidentalMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "人员杂费修改接口", notes = "人员杂费修改")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult update(@RequestBody @Validated UpdateEmpIncidentalTO updateEmpIncidentalTO) {
        try {
            return toAjax(tlEmpIncidentalService.update(updateEmpIncidentalTO)) ;
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_emp_incidental", idKey = "ids", bean = TlEmpIncidental.class, beanMapper = TlEmpIncidentalMapper.class,
            names = "empid", twoBeanMapper = TlEmployeeMapper.class, twoNames = "name", twoTableName = "tl_employee")
    @ApiOperation(value = "人员杂费删除接口", notes = "人员杂费删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "deletebyid", method = RequestMethod.POST)
    public AjaxResult deletebyid(@RequestBody @Validated ForIdsTO forIdsTO) {
        try {
            return toAjax(tlEmpIncidentalService.deletebyid(forIdsTO));
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @ApiOperation(value = "人员杂费详情接口", notes = "人员杂费详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public AjaxResult getDetail(@RequestBody @Validated EmpIncidentalForIdTO empIncidentalForIdTO) {
        try {
            TlEmpIncidental tlEmpIncidental = tlEmpIncidentalService.getDetail(empIncidentalForIdTO);
            return AjaxResult.success(tlEmpIncidental);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    @ApiOperation(value = "人员杂费列表接口", notes = "人员杂费列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = EmpIncidentalForListVO.class)
    })
    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult getList(@Validated @RequestBody EmpIncidentalListForPageTO empIncidentalListTo) {
        try {
            return AjaxResult.success(tlEmpIncidentalService.getList(empIncidentalListTo));
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    /**
     * 人员杂费导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_emp_incidental", bean = TlEmpIncidental.class, beanMapper = TlEmpIncidentalMapper.class, names = "empdeptid, empid")
    @ApiOperation(value = "人员杂费导入接口", notes = "人员杂费导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @ModelAttribute @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlEmpIncidental> util = new ExcelUtil<TlEmpIncidental>(TlEmpIncidental.class);
            List<TlEmpIncidental> empIncidentalList = util.importExcel(inputStream);
            if (empIncidentalList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlEmpIncidentalService.excelReader(empIncidentalList);
            if (tlEmpIncidentalService.saveBatch(empIncidentalList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception exception) {
            exception.printStackTrace();
            return AjaxResult.fail();
        }

    }

    @ApiOperation(value = "人员杂费导出接口", notes = "人员杂费导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = EmpIncidentalExcelOutVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody EmpIncidentalListTO empIncidentalListTo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((empIncidentalListTo.getIds()!=null&&empIncidentalListTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlEmpIncidental> empIncidentalList = tlEmpIncidentalService.getTlEmpIncidental(empIncidentalListTo, format);
            //工具类实例化
            ExcelUtil<EmpIncidentalExcelOutVO> util = new ExcelUtil<EmpIncidentalExcelOutVO>(EmpIncidentalExcelOutVO.class);
            //数据载体转换
            List<EmpIncidentalExcelOutVO> empIncidentalExcelOutVOList = JSONObject.parseArray(JSONObject.toJSONString(empIncidentalList), EmpIncidentalExcelOutVO.class);
            //构造结果集
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            Map<String, TlEmployee> employeeMap = employeeService.getEmpMap(new QueryWrapper<>());
            for (EmpIncidentalExcelOutVO empIncidentalExcelOutVO : empIncidentalExcelOutVOList) {
                if (departMap.containsKey(empIncidentalExcelOutVO.getEmpdeptid())) {
                    empIncidentalExcelOutVO.setEmpdeptName(departMap.get(empIncidentalExcelOutVO.getEmpdeptid()).getDepartName());
                }
                if (StringUtils.isNotEmpty(empIncidentalExcelOutVO.getPaydate())) {
                    empIncidentalExcelOutVO.setPaydateString(format.format(empIncidentalExcelOutVO.getPaydate()));
                }
                if(employeeMap.containsKey(empIncidentalExcelOutVO.getEmpid())){
                    empIncidentalExcelOutVO.setWorktypename(employeeMap.get(empIncidentalExcelOutVO.getEmpid()).getWorktypename());
                }
                if(employeeMap.containsKey(empIncidentalExcelOutVO.getEmpid())){
                    empIncidentalExcelOutVO.setEmplnum(employeeMap.get(empIncidentalExcelOutVO.getEmpid()).getEmplnum());
                }
                if(employeeMap.containsKey(empIncidentalExcelOutVO.getEmpid())){
                    empIncidentalExcelOutVO.setIdcardnum(employeeMap.get(empIncidentalExcelOutVO.getEmpid()).getIdcardnum());
                }
                if(employeeMap.containsKey(empIncidentalExcelOutVO.getEmpid())){
                    empIncidentalExcelOutVO.setEmNpame(employeeMap.get(empIncidentalExcelOutVO.getEmpid()).getName());
                }
            }
            //            导出
            empIncidentalExcelOutVOList = empIncidentalExcelOutVOList.stream().sorted(Comparator.comparing(EmpIncidentalExcelOutVO::getPaydateString).reversed()).collect(Collectors.toList());
            return util.exportExcel(empIncidentalExcelOutVOList, "人员杂费");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "人员杂费导出模板接口", notes = "人员杂费模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = EmpIncidentalExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<EmpIncidentalInExcelOutVO> util = new ExcelUtil<EmpIncidentalInExcelOutVO>(EmpIncidentalInExcelOutVO.class);
            //数据载体转换
            List<EmpIncidentalInExcelOutVO> empIncidentalInExcelOutVOList = new ArrayList<>();
            //导出
            return util.exportExcel(empIncidentalInExcelOutVOList, "人员杂费模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

